package Cantella::DJabberd::Web::UI::ViewPort::Menu;

use Reaction::Class;
use aliased 'Cantella::DJabberd::Web::UI::ViewPort::MenuItem';
extends 'Reaction::UI::ViewPort';

has item_order => ( is => 'rw', isa => 'ArrayRef');
has _item_map  => ( is => 'rw', isa => 'HashRef',  required => 1, default => sub {{}});
has ordered_items => ( is => 'rw', isa => 'ArrayRef', lazy_build => 1 );
has current_item  => ( is => 'rw', isa => 'Str' );

sub _build_ordered_items {
  my $self = shift;
  my @spec = $self->has_item_order ? $self->item_order : [];
  my $ordered = $self->sort_by_spec( \@spec, [ keys %{ $self->_item_map } ]);
    return [ @{ $self->_item_map }{ @$ordered } ];
}

around current_item => sub {
  my $orig = shift;
  if(@_ > 1){
    # only set if it exists
    if( $_[0]->has_item($_[1]) ){
      return $orig->( @_ );
    }
    }
  return $orig->(@_);
};

sub has_item {
  my ($self, $name) = @_;
  exists $self->_item_map->{$name};
}

sub item {
  my ($self, $name) = @_;
  if(defined(my $item = $self->_item_map->{$name})){
    return $item;
  }
}

sub add_item {
  my ($self, $name, %opts) = @_;
  $self->_item_map->{$name} = MenuItem->new
    (
     ctx      => $self->ctx,
     name     => $name,
     location => join('-', $self->location, $name),
     @_,
    );
}

__PACKAGE__->meta->make_immutable;

1;

__END__;
